package com.example.sonone.xianliusuanfa;

import java.util.Random;

/**
 *  漏桶算法
 */
public class LeakyBucket {

    public long timeStamp = System.currentTimeMillis(); // 当前时间
    public long capacity = 100; // 桶的容量
    public long rate = 20; // 水漏出的速度(每秒系统能处理的请求数)
    public long water = 0; // 当前水量(当前累积请求数)

    public boolean limit() throws InterruptedException {
        long now = System.currentTimeMillis();
        water = Math.max(0, water - ((now - timeStamp) / 1000) * rate); // 水漏 剩下的数量
        timeStamp = now;
        if ((water + 1) < capacity) {
            // 尝试加水,并且水还未满
            water += 1;
            System.out.println(" water"+water);
            return true;
        } else {
            // 水满，拒绝加水
            System.out.println(" 水加满了，等待3s,释放水资源");
            Thread.sleep(3000);
            System.out.println(" 释放完成 ");
            water = 0;
            return false;
        }
    }

    public static void main(String[] args) throws Exception {
        LeakyBucket l = new LeakyBucket();
        while (true) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    boolean limit = false;
                    try {
                        limit = l.limit();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(limit);
                }
            }).start();
            try {
                Thread.sleep(new Random().nextInt(10));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
